<?php


namespace app\admin\controller\system;


use app\admin\model\ProductErrorType;
use app\admin\model\SystemConfig;
use app\admin\model\SystemFinanceDay;
use app\admin\service\TriggerService;
use app\admin\traits\BuildHtml;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;

/**
 * Class Config
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="系统配置管理")
 */
class Config extends AdminController
{
    use BuildHtml;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new SystemConfig();

    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        //收费规则单独查询和设置
        $map_rule = [
            'group' => 'rule',
            'hide' => 0,
        ];
        $rule = $this->model->where($map_rule)->order('sort asc')->select();
        //小程序规则单独查询和设置
        $map_rule = [
            'group' => 'applet',
            'hide' => 0,
        ];
        $applet = $this->model->where($map_rule)->order('sort asc')->select();
//        $applet_html = $this->buildConfigs($applet);
        return $this->fetch('', ['rule' => $rule, 'applet' => $applet/*,'html'=>$applet_html*/]);
    }

    /**
     * @NodeAnotation(title="保存")
     */
    public function save()
    {
        $post = $this->request->post();
        $reset = false;
        try {
            foreach ($post as $key => $val) {
                if ($key == 'rule_system_reset') {//清表请求不入库
                    $val && ($reset = true);
                    $code = $val;
                    continue;
                } elseif ($val != sysconfig(true, $key)) {//正常规则有改变的自动更新
                    $this->model->where('name', $key)->update(['value' => $val]);
                }
                //某些配置需要单独添加到表里
                $this->ex_rule_in_table($key, $val);
            }
            TriggerService::updateMenu();
            TriggerService::updateSysconfig();
        } catch (\Exception $e) {
            $this->error('保存失败' . $e->getMessage());
        }
        if (isset($code)) {
            $reset && $this->reset_system($code);
        }
        $this->success('保存成功');
    }

    //特殊的规则需要入表
    private function ex_rule_in_table($key, $val)
    {
        if ($key == 'rule_error_type') {
            (new ProductErrorType)->set_error_type($val);
        }/*elseif($key == 'rule_change_type'){
            (new UserChangeType())->set_change_type($val);
        }*/
        return true;
    }

    /**
     * 系统数据重置
     * @param $code
     */
    private function reset_system($code)
    {
        env('ADMIN.IS_ONLINE', true) && $this->error('系统已上线，不允许重置');
        if ($code == 'truncate finance') {
            $tb_truncate = [
                'cashcard_cate', 'cashcard_user',
                'shop_finance_day', 'system_finance_day',
                'user_order'
            ];
        }else {
            ($code != config('app.reset_pass')) && $this->error('重置码输入错误');
            $tb_truncate = [
                /*'product_base',*/
                'product_report', 'product_order', 'product_log',//清空设备记录
                'user_base', 'user_money_change', 'user_recharge',//清空会员记录
                'system_finance_day',//系统统计表
            ];
        }

        $prefix = env('database.prefix');
        foreach ($tb_truncate as $tb_name) {
            $sql = 'truncate ' . $prefix . $tb_name . ';';
            Db::execute($sql);
        }
    }

    public function randomEchartsData(){
        SystemFinanceDay::init()->createTestRecords();
        dd(123);
    }


}